package io.renren.modules.sp.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.renren.common.annotation.SeasonFilter;
import io.renren.common.interceptor.DataScope;
import io.renren.common.page.PageData;
import io.renren.common.service.impl.CrudServiceImpl;
import io.renren.common.constant.Constant;
import io.renren.common.utils.DateUtils;
import io.renren.common.utils.IOUtils;
import io.renren.common.utils.Result;
import io.renren.common.utils.ZipUtils;
import io.renren.modules.sp.dao.SpMatchDao;
import io.renren.modules.sp.dao.SpMatchItemDao;
import io.renren.modules.sp.dao.SpMatchItemTeamDao;
import io.renren.modules.sp.dto.SpMatchDTO;
import io.renren.modules.sp.entity.SpMatchEntity;
import io.renren.modules.sp.entity.SpMatchItemEntity;
import io.renren.modules.sp.entity.SpMatchItemTeamEntity;
import io.renren.modules.sp.service.SpMatchItemTeamService;
import io.renren.modules.sp.service.SpMatchService;
import io.renren.modules.security.user.SecurityUser;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.*;

/**
 * 赛事
 *
 * @author whc 15953295779@126.com
 * @since 3.0 2023-04-21
 */
@Service
public class SpMatchServiceImpl extends CrudServiceImpl<SpMatchDao, SpMatchEntity, SpMatchDTO> implements SpMatchService {

    @Autowired
    private SpMatchItemDao spMatchItemDao;
    @Autowired
    private SpMatchItemTeamDao spMatchItemTeamDao;
    @Autowired
    private SpMatchItemTeamService spMatchItemTeamService;

    @Override
    public QueryWrapper<SpMatchEntity> getWrapper(Map<String, Object> params){
        QueryWrapper<SpMatchEntity> wrapper = new QueryWrapper<>();

        String matchName = (String)params.get("matchName");
        wrapper.like(StringUtils.isNotBlank(matchName), "match_name", matchName);
        String matchLevel = (String)params.get("matchLevel");
        wrapper.eq(StringUtils.isNotBlank(matchLevel), "match_level", matchLevel);
        String season = (String)params.get("season");
        wrapper.eq(StringUtils.isNotBlank(season), "season", season);
        Long adminId = (Long)params.get("adminId");
        wrapper.eq(adminId!=null, "admin_id", adminId);
        //省筛选
        String province = (String)params.get("province");
        wrapper.eq(StringUtils.isNotBlank(province), "province", province);
        //市筛选
        String city = (String)params.get("city");
        wrapper.eq(StringUtils.isNotBlank(city), "city", city);
        //自定义sql
        DataScope dataScope = (DataScope)params.get("sqlFilter");
        if(dataScope!=null){
            String sqlFilter = dataScope.getSqlFilter();
            if(StringUtils.isNotEmpty(sqlFilter)){
                wrapper.apply(sqlFilter);
            }
        }
        return wrapper;
    }

    //分页获取赛事列表
    @Override
    @SeasonFilter(tableAlias = "mc")
    public PageData<SpMatchDTO> queryPage(Map<String, Object> params) {
        /*
        String matchLevel = (String)params.get("matchLevel");
        String matchName = (String)params.get("matchName");
        String season = (String)params.get("season");
        //省筛选
        String province = (String)params.get("province");
        //市筛选
        String city = (String)params.get("city");
        IPage<SpMatchEntity> page = baseDao.selectPage(
                getPage(params, null, false),
                new QueryWrapper<SpMatchEntity>()
                        .like(StringUtils.isNotBlank(matchName), "match_name", matchName)
                        .eq(StringUtils.isNotBlank(matchLevel), "match_level", matchLevel)
                        .eq(StringUtils.isNotBlank(province), "province", province)
                        .eq(StringUtils.isNotBlank(city), "city", city)
                        .eq(StringUtils.isNotBlank(season), "season", season)
                        .eq(params.get("adminId")!=null ,"admin_id", params.get("adminId"))
                        .or()
                        .eq(params.get("adminId")!=null, "admin_item_id", params.get("adminId"))


        );*/
        Page page = createPage(params);
        //分页参数
        params.put(Constant.PAGE, page);
        IPage<SpMatchEntity> page2 = baseDao.selectPageBy(page, params);
        return getPageData(page2, SpMatchDTO.class);
    }

    // 根据管理员来查询赛事
    @Override
    @SeasonFilter(tableAlias = "t")
    public List<SpMatchEntity> queryPageByAdmin(Map<String, Object> params) {
        Long adminId = (Long) params.get("adminId");
        return this.baseDao.selectList(new QueryWrapper<SpMatchEntity>().eq("admin_id", adminId));
    }

    /**
     * 生成参赛编号
     * 生成参赛编号，不能刷状态
     * @param matchId
     */
    @Override
    //@Transactional
    public void generateTicketNo(Long matchId) {
        // 查询国赛20下的所有赛项
        List<SpMatchItemEntity> itemList = spMatchItemDao.selectList(new QueryWrapper<SpMatchItemEntity>()
                .eq("match_id", matchId)
        );

        List<Long> itemIds = new ArrayList<>();
        for (SpMatchItemEntity item : itemList){
            itemIds.add(item.getId());
        }

        // 查询审核通过的数据 1,2,4,5,6
        // 0审核中 1报名成功 2完赛 3已取消 4比赛中 5已获晋级资格 6晋级成功 7弃权 8驳回 9待确认 10报名未成功
        List<SpMatchItemTeamEntity> matchItemTeamEntityList = spMatchItemTeamDao.selectList(
                new QueryWrapper<SpMatchItemTeamEntity>()
                        .in("status", 1,2,4,5,6)
                        .in("match_item_id", itemIds)
                        //.in("match_item_id", 74,77)
                        //.eq("group_id", 100301)
                        //.eq("team_id", 1218)
        );
        for (SpMatchItemTeamEntity team : matchItemTeamEntityList) {
            SpMatchItemTeamEntity entity = spMatchItemTeamDao.selectById(team.getId());
            // 审批后生成参赛编号
            try {
                String errorMsg = spMatchItemTeamService.generateTicketNo(entity.getId());
                if (StringUtils.isNotBlank(errorMsg)) {
                    System.out.println("生成编号失败:" + errorMsg);
                } else {
                    spMatchItemTeamDao.updateById(entity);
                }
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println("生成编号失败:" + e.getMessage());
            }
        }
    }

    /**
     * 下载li领队照片
     *
     * @param
     * @param response
     * @throws Exception
     */
    @Override
    public Result<String> downloadLeaderHeaderFile(Map<String, Object> params, HttpServletResponse response) throws Exception {
        String matchName = (String) params.get("matchName");
        Long matchItemId = Long.parseLong((String) params.get("matchId"));
        List<Map<String, Object>> list = spMatchItemDao.queryLeaderHeader(matchItemId);
        //list移除集合中entryPic字段等于空的数据
        List<Map<String, Object>> urlList = new ArrayList<>();
        //把list中的entryPic字段不为空的取出来放到urlList中
        Map<String, Object> urlMap = null;
        for (Map<String, Object> map : list) {
            urlMap = new HashMap<>();
            urlMap.put("url", map.get("header"));
            urlMap.put("ticket", map.get("real_name") + "-" + map.get("ticket"));
            urlList.add(urlMap);
        }
        if (list.size() > 0) {
            //清空输出流
            response.reset();
            //定义输出类型
            response.setContentType("application/octet-stream");
            // 赛事+筛选条件+参赛证/号码布+月日.zip
            //[赛事名]-[赛项名]-[下载日期]-参赛照片.zip
            String title = matchName + "-" + DateUtils.format(new Date(), "MMdd") + "-领队照片.zip";
            // 编译成utf-8格式
            title = URLEncoder.encode(title, "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + title + ";" + "filename*=utf-8''" + title);
            // 打包下载
            ZipUtils.getZipFile(IOUtils.getByte(urlList), response.getOutputStream(), response);
            return new Result<String>().ok("下载成功");
        } else {
            return new Result<String>().error("没有可下载的数据");
        }
    }



    @Override
    public List<Map<String,Object>> exportLeaderForm(Map<String, Object> params) throws Exception {
        Long matchId = Long.parseLong((String) params.get("matchId"));
        return spMatchItemDao.queryLeaderForm(matchId);
    }



}